import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Input, Button, Modal, message, Form, Row, Col, List } from 'antd';
import axios from './../../axios';
import baseURL from './../../config/baseurl';
import emptyicon from './../../statics/icon/empty.svg';
import Utils from './../../utils/utils';
import {getCsrfToken} from './../../utils/common';
import TreeFolder from './../../components/TreeFolder';
import { setCookie } from './../../utils/common';
import iconList from './../../config/suffixIcon';
import jqmlogo from './../../statics/img/jqm-logo.png';
import './index.less';
const FormItem = Form.Item;
class User extends Component {
	
	//登录表单
	formRef = React.createRef();
	
	state={
		logo: baseURL + "/static/media/system_logo.png?" + Date.now(),
		tips: "等待验证...",
		isLogin: false,//是否登录
		loginModal: false,//登录模态框
		isError: true,//链接是否异常
		hasPwd: true,//是否需要密码
		userName: "",//登录用户名
		codeSrc: "",//登录图形验证码
		fileid: "",//检测密码后真实的fileid文件id
		createuser: "",//分享者
		isTreeFolderVisible: false,//保存到网盘模态框
	}
	
	componentDidMount(){	
		//检测是否登录
		this.loginCheck();
	}
	
	//检测是否登录
	loginCheck = () => {
		axios.ajax({
			url: "/User/Login/loginCheck",
			method: "get"
		}).then(res => {
			if(res.result){//已登录
				//获取用户名
				axios.ajax({
					url: "/user/Login/getUserInfo",
					method: "get"
				}).then(res => {
					if(res.result){
						let username = res.result.user_name;
						this.setState({isLogin: true, userName: username});
					}
				})
				//获取文件id,
				const fileid = this.props.match.params.id;
				const index = fileid.indexOf("密码");
				if(index > 0){
					this.checkLink(fileid.slice(0, index));//检测是否需要密码
				}else{
					this.checkLink(fileid);//检测是否需要密码
				}
			}else{//未登录
				message.info("请先登录");
				this.getCode();//获取图形验证码
				this.setState({loginModal: true});//打开登录模态框
			}
		}).catch(err => {
		})
	}
	
	//获取图形验证码
	getCode = ()=> {
		axios.ajax({
			url: "/User/Login/getVerifyCode",
			method: "get"
		}).then(res=>{
			if(res.code === 0){
				this.setState({
					codeSrc: res.result
				})
			}
		})
	}
	
	//登录
	onFinish = values => {
		this.setState({loginModal: false});//关闭登录模态框
		axios.ajax({
			url: "/User/Login/login",
			method: "post",
			data: values
		}).then(res=>{
			if(res.code === 0){
				setCookie('login', true, 180);
				//获取文件id,
				const fileid = this.props.match.params.id;
				const index = fileid.indexOf("密码");
				if(index > 0){
					this.checkLink(fileid.slice(0, index));//检测是否需要密码
				}else{
					this.checkLink(fileid);//检测是否需要密码
				}
				this.setState({isLogin: true, userName: values.username })
			}
		}).catch(err=>{
			if(err.code === 1101){
				this.formRef.current.setFieldsValue({"verify_code":""});
			}
			this.getCode();
		})
	}
	
	//检测是否需要密码
	checkLink = (fileid) => {
		axios.get({
			url: "/share/shareLink/checkLinkCode", 
			params: {fileid}
		}).then(res=>{
			if(res.code === 0){
				this.setState({ 
					fileid: res.result.fileid, 
					hasPwd:res.result.is_need_pwd, 
					isError: false,
				});
				if(res.result && !res.result.is_need_pwd){
					this.getFileList(res.result.fileid);//获取分享链接的文件列表
				}
			}else{
				Modal.warning({
					title: '提示',
					content: '请联系好友重新分享',
				});
			}
		}).catch(err=>{
			Modal.warning({
				title: '提示',
				content: err.msg + '，请联系好友重新分享',
				okText: "好的"
			});
		})
	}
	
	//输入提取码
	onChange = e => {
		this.setState({inputValue: e.target.value})
	}
	
	//输完提取码提交
	submit = () => {
		axios.ajax({
			url: "/share/shareLink/checkLinkCodeIsRight", 
			method: "post",
			data: {fileid: this.state.fileid, pwd: this.state.inputValue}
		}).then(res=>{
			if(res.code === 0){
				this.setState({hasPwd: false});
				this.getFileList(this.state.fileid);//获取分享链接的文件列表
			}
		})
	}
	
	//获取分享链接的文件列表
	getFileList = (fileid) => {
		axios.get({
			url: "/share/shareLink/shareListContentFromLink", 
			params: {fileid, size: 100, id_for_check: fileid}
		}).then(res=>{
			if(res.code === 0){
				let data = [];
				let createuser = "";//分享者
				let createuserId = "";//分享者id
				let tips = "";
				if(res.result){
					data = res.result.list.map(item=>{
						createuserId = item.creatorid;
						return {
							name: item.filename,
							time: Utils.formateTime(item.mtime), 
							icon: item.mimetype,
							size: Utils.mertic(item.size),
							fileid: item.fileid
						}
					})
				}else{
					tips= "文件异常，请联系分享者重新分享"
				}
				//获取分享者名称，最好上个接口后台直接返回名称，不用这里再比对一次
				//获取网盘所有用户
				axios.get({
					url:"/files/group/getUsers"
				}).then(res => {
					if(res.code === 0){
						for(let val of res.result){
							if(val.id === createuserId){
								createuser = val.user_name;
							}
						}
						
						this.setState({data, createuser, tips});
					}
				})
			}
		})
	}
	
	//下载
	handleDownloader = () => {
		const data = this.state.data;
		if(data && data.length > 0){
			for(let val of data){
				window.open( baseURL + "/files/download/shareLink?fileid=" + val.fileid + "&CSRF=" + getCsrfToken());
			}
		}else{
			message.error("无法下载")
		}
	}
	
	//点击保存到网盘
	handleSave = () => {
		const data = this.state.data;
		if(data && data.length > 0){
			this.setState({isTreeFolderVisible: true});
		}else{
			message.error("文件异常，无法保存");
		}
	}

	
	//保存到网盘选中文件夹
	dirChecked = (fileid) => {
		this.setState({dirCheckedId: fileid});
	}
	
	//保存到网盘
	dirCheckedSubmit = () => {
		this.setState({isTreeFolderVisible: false});
		const destid = this.state.dirCheckedId;//选中的文件夹
		const data = this.state.data;
		if(!data){
			message.error("无法保存");
			return;
		}
		for(let val of data){
			axios.ajax({
				url: "/share/shareLink/saveFiles", 
				method: "post",
				data: { fileId: val.fileid, savePathId: destid, id_for_check: this.state.fileid }
			}).then(res=>{
				if(res.code === 0){
					message.success("保存成功");
				}else{
					message.error("保存失败");
				}
			})
		}
	}
	
	//logo加载失败
	imgError = () => {
		this.setState({
			logo: jqmlogo
		})
	}
	
	render(){
		const color = localStorage.getItem("color");
		const { logo, loginModal, isError, hasPwd, data, createuser, isTreeFolderVisible } = this.state;
		return (
			<div className="share-page">
				<div className="share-header">
					<div className="header-wrap">
						<div className="header-left">
							<Link to="/main/whole">
								<div className="logo-wrap">
									<img src={logo} alt="" onError={this.imgError} />
									<h1 style={{color: color}}>JesCloud企业网盘</h1>
								</div>
							</Link>
						</div>
						<div className="header-right">
							{this.state.isLogin?
								<span>{this.state.userName}</span>:
								<span onClick={()=>this.setState({loginModal: true})}>登录</span>
							}
						</div>
					</div>
				</div>
				{isError ?
					<div className="empty-page">
						<div>
							<img src={emptyicon} alt="空" />
							<p>{this.state.tips}</p>
						</div>
					</div>
					: hasPwd ?
					<div className="haspwd-wrap">
						<div className="haspwd-wrap-content">
							<p>请输入提取码</p>
							<Input value={this.state.inputValue} onChange={this.onChange} />
							<Button type="primary" onClick={this.submit}>确定</Button>
						</div>
					</div>
					:
					<div>
						<div className="share-createuser">
							来自 {createuser} 的分享
						</div>
						<div className="share-filelist">
							<List
								itemLayout="horizontal"
								dataSource={data}
								renderItem={item => (
									<List.Item>
										<svg
											className="icon share-list-icon"
											aria-hidden="true"
										>
											<use xlinkHref={iconList[item.icon]}></use>
										</svg>
										<List.Item.Meta
											title={item.name}
											description={`大小:${item.size}  分享时间:${item.time}`}
										/>
									</List.Item>
								)}
							/>
						</div>
						<div className="share-button-wrap">
							<Button type="primary" onClick={this.handleDownloader}>下载</Button>
							<Button onClick={this.handleSave}>保存到网盘</Button>
						</div>
					</div>
				}
				<div className="footer">
					<span>金钱猫科技股份有限公司</span>|
					<span>服务热线：0591-83268695</span>|
					<span>联系传真：0591-83295875</span>|
					<span>公司网址:
						<a href="http://www.jqmkj.com">http://www.jqmkj.com</a>
					</span>|
					<span>联系地址：福州台江区江滨路58号</span>
				</div>
				<Modal
					visible={loginModal}
					title="登录"
					footer={null}
					onCancel={()=>this.setState({loginModal: false})}
					width={350}
				>
					<Form 
						ref={this.formRef}
						onFinish={this.onFinish}
						className="login-form"
					>
					    <FormItem
							name="username"
							hasFeedback
							validateTrigger="onChange"
							maxLength={30}
							rules={[
								{required: true, message: "请输入账号"},
								{min:5,max:16,message:" "},
								{pattern: /^\w+$/g, message: " "}
							]}
						>
					        <Input placeholder="账号" autoComplete="off" />
					    </FormItem>
					    <FormItem
							name="pwd"
							hasFeedback
							maxLength={30}
							validateTrigger="onChange"
							rules={[
								{required: true, message: "请输入密码"},
								{min:6,max:18,message:" "},
								{pattern: /^[a-z0-9_]{3,16}$/, message: " "}
							]}
						>
							<Input.Password placeholder="密码" autoComplete="off" />
					    </FormItem>
						<FormItem noStyle>
							<Row gutter={20}>
								<Col span={12}>
									<FormItem
										name="verify_code"
										hasFeedback
										validateTrigger="onChange"
										rules={[
											{required: true, message: '请输入验证码'},
											{min:4,max:4,message:" "},
											{pattern: /^\w+$/g, message: " "}
										]}
									>
										<Input 
											maxLength={4}
											placeholder="验证码" 
											autoComplete="off"
										/>
									</FormItem>
								</Col>
								<Col span={12}>
									<img 
										src={this.state.codeSrc} 
										alt="验证码" 
										className="code-img"
										onClick={this.getCode}
									/>
								</Col>
							</Row>
						</FormItem>
					    <FormItem>
					        <Button type="primary" htmlType="submit" className="login-form-button">
					            登录
					        </Button>
					    </FormItem>
					</Form>
				</Modal>
				<Modal
					visible={isTreeFolderVisible}
					title="保存到网盘"
					okText="确认"
					cancelText="取消"
					onOk={this.dirCheckedSubmit}
					onCancel={()=>this.setState({isTreeFolderVisible: false})}
				>
					<TreeFolder dirChecked={this.dirChecked} />
				</Modal>
			</div>
		)
	}
}

export default User;